package com.kye.express.business.freight_rates_query;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseToolbarActivity;
import com.kye.express.business.scanner.ScannerActivity;
import com.kye.express.databinding.ActivityNumberQueryBinding;
import com.kye.express.utils.PhoneUtils;
import com.kye.express.utils.StringUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.freight_rates_query.QueryWaybillCostResultBean;
import com.kye.model.bean.freight_rates_query.QueryWaybillErrorCountModel;
import com.kye.model.constant.Constants;

import io.reactivex.functions.Consumer;

/**
 * 单号查询
 */
public class NumberQueryActivity extends BaseToolbarActivity implements NumberQueryActivityContract.NumberQueryActivityView {
    private static final int REQUEST_CODE_SCANNER = 1;
    private ActivityNumberQueryBinding mBinding;
    private Context mContext;
    private NumberQueryActivityContract.NumberQueryActivityViewPresenter mPresenter;

    private QueryWaybillErrorCountModel mQueryErrCountBean;
    private boolean mIsNeedsetPhone = false;
    private Dialog mDialog;

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, NumberQueryActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_number_query);
        mPresenter = new NumberQueryActivityContract.NumberQueryActivityViewPresenter(this);
        mPresenter.bind(this);
        mContext = this;
        setUpToolbar((Toolbar) findViewById(R.id.toolbar));
        setTitle(getString(R.string.frq_number_query));
        initView();
        initEvent();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.unbind();
        }
    }

    private void initView() {
        mQueryErrCountBean = mPresenter.getQueryWaybillErrorCount();
    }

    private void initEvent() {
        RxView.clicks(mBinding.btnQuery)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if ((mQueryErrCountBean.getErrCount() + 1) >= 50) {
                            MaterialDialog dialog = new MaterialDialog.Builder(mContext)
                                    .content(R.string.frq_error_count_query_max)
                                    .negativeText(R.string.common_know)
                                    .show();
                        } else {
                            String errorString = checkParams();
                            if (!StringUtils.isNullOrEmpty(errorString)) {
                                ToastManager.show(mContext, errorString, Toast.LENGTH_SHORT);
                                return;
                            }
                            String number = StringUtils.checkStringIsNull(mBinding.edtWaybill.getText().toString().trim().replace(" ", ""));
                            String phone = StringUtils.checkStringIsNull(mBinding.edtPhone.getText().toString().trim().replace(" ", ""));
                            mPresenter.queryWaybillCost(number, phone);
                        }
                    }
                });

        RxView.clicks(mBinding.ivScan)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        startActivityForResult(new Intent(mContext, ScannerActivity.class), REQUEST_CODE_SCANNER);
                    }
                });

        RxTextView.textChanges(mBinding.edtWaybill).cache()
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<CharSequence>() {
                    @Override
                    public void accept(CharSequence charSequence) throws Exception {
                        mIsNeedsetPhone = false;
                        mBinding.edtPhone.setText("");
                        mBinding.edtPhone.setVisibility(View.GONE);
                        mBinding.tvPhoneTips.setVisibility(View.GONE);
                        mBinding.tvPrice.setText("￥0.00");
                        mBinding.tvPrice.setTextColor(getResources().getColor(R.color.black_999));
                    }
                });
    }

    public String checkParams() {
        StringBuilder builder = new StringBuilder();
        String number = StringUtils.checkStringIsNull(mBinding.edtWaybill.getText().toString().trim());
        String phone = StringUtils.checkStringIsNull(mBinding.edtPhone.getText().toString().trim());
        if (StringUtils.isNullOrEmpty(number) || StringUtils.isNullOrEmpty(number.replace(" ", ""))) {
            builder.append(getString(R.string.frq_waybill_is_null));
        } else {
            number = number.replace(" ", "");
            if (number.length() != 7 && number.length() != 11) {
                builder.append(getString(R.string.frq_waybill_not_exist));
                mQueryErrCountBean.setErrCount(mQueryErrCountBean.getErrCount() + 1);
                mPresenter.setQueryWaybillErrorCount(mQueryErrCountBean);
            }
        }

        if (StringUtils.isNullOrEmpty(builder.toString().trim()) && mIsNeedsetPhone) {
            if (StringUtils.isNullOrEmpty(phone)) {
                builder.append(getString(R.string.frq_phone_not_null));
            } else {
                phone = phone.replace(" ", "");
                if (phone.length() != 7 && phone.length() != 8 && phone.length() != 11) {
                    builder.append(getString(R.string.frq_error_for_phone));
                    mQueryErrCountBean.setErrCount(mQueryErrCountBean.getErrCount() + 1);
                    mPresenter.setQueryWaybillErrorCount(mQueryErrCountBean);
                }
            }
        }
        return builder.toString();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SCANNER && data != null) {
            String waybill = data.getStringExtra(ScannerActivity.KEY_SCANNER_RESULT);
            if (!TextUtils.isEmpty(waybill)) {
                mBinding.edtWaybill.setText(waybill);
            }
        }
    }

    @Override
    public void onLoaded(OpenApiResult<QueryWaybillCostResultBean> result) {
        if (result != null) {
            handleResult(result);
        }
    }

    @Override
    public void onComplete() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    @Override
    public void onError(String msg) {
        ToastManager.show(mContext, msg, Toast.LENGTH_SHORT);
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    @Override
    public void onApiError(OpenApiResult<QueryWaybillCostResultBean> result) {
        if (result != null) {
            handleResult(result);
        }
    }

    @Override
    public void onLoading() {
        if (mDialog == null) {
            mDialog = new KyeProgressDialog.Builder(mContext).build();
        }
        mDialog.show();
    }

    public void handleResult(OpenApiResult<QueryWaybillCostResultBean> result) {
        switch (result.getCode()) {
            case 0:
                mBinding.edtPhone.setVisibility(View.GONE);
                mBinding.tvPhoneTips.setVisibility(View.GONE);
                if (result.getData() != null) {
                    mBinding.tvPrice.setText("￥" + result.getData().getMoney());
                    mBinding.tvPrice.setTextColor(getResources().getColor(R.color.frq_price_color));
                }
                break;
            case 32837:
                mIsNeedsetPhone = true;
                mBinding.edtPhone.setVisibility(View.VISIBLE);
                mBinding.tvPhoneTips.setVisibility(View.VISIBLE);
                break;
            case 32834:
                new MaterialDialog.Builder(mContext)
                        .title(R.string.frq_dialog_title_mounth)
                        .content(R.string.frq_dialog_message_mounth)
                        .positiveText(R.string.frq_contact_kye)
                        .negativeText(R.string.common_know)
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.dismiss();
                                PhoneUtils.call(NumberQueryActivity.this,Constants.KYE_PHONE_NUMBER);
                            }
                        })
                        .onNegative(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.dismiss();
                            }
                        })
                        .show();
                break;
            case 30005:
            case 32838:
            case 33510:
            case 32835:
            case 32836:
                new MaterialDialog.Builder(mContext)
                        .content(result.getMsg())
                        .negativeText(R.string.common_know)
                        .show();
                break;
        }
    }
}
